package hf.tries

import akka.actor.ActorSystem
import akka.event.slf4j.SLF4JLogging
import akka.pattern.{CircuitBreaker, CircuitBreakerOpenException}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.language.postfixOps
import scala.concurrent.duration._
import scala.util.Random

/**
  * 贲国称 于 16/9/9 创建。
  */
object TryCB extends App with SLF4JLogging {
  def call(): String = {
    val sleep = Math.abs(Random.nextInt % 20)
    Thread.sleep(sleep * 100)
    "OK"
  }
  implicit val system = ActorSystem("CB")
  val cb = CircuitBreaker(system.scheduler, 3, 1 seconds, 5 seconds)
  cb.onClose({
    log.info("CB closed")
  })
  cb.onHalfOpen({
    log.info("CB half opened")
  })
  cb.onOpen({
    log.info("CB opened")
  })
  for (i <- 1 to 100) {
    println("call ...")
    try {
      println(cb.withSyncCircuitBreaker[String](call()))
    } catch {
      case e: CircuitBreakerOpenException =>
        Thread.sleep(500)
      case t: Throwable =>
        log.error(s"Exception: ${t.getMessage}")
    }
  }
}
